﻿namespace DataIntegration.Extracters.FlatFile
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Reflection;
    using DataIntegration.Messaging.Consumer;
    using DataIntegration.Messaging.Publisher;
    using Entities.Triggers;
    using log4net;
    using Storage;

    public class FlatFileExtracter : TriggeredExtracter
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private readonly IDictionary<string, string> columns;

        private readonly string file;

        private readonly bool hasHeaderRow;

        public FlatFileExtracter(
                string name,
                IPublisherFactory publisherFactory,
                IDataStoreFactory dataStoreFactory,
                string filter,
                IConsumerFactory consumerFactory,
                string triggerTopic,
                string file,
                bool hasHeaderRow)
            : base(name, publisherFactory, dataStoreFactory, filter, consumerFactory, triggerTopic)
        {
            Logger.DebugFormat(
                "Creating FlatFileExtracter with file=[{0}] hasHeaderRow=[{1}]",
                file,
                hasHeaderRow);
            this.file = file;
            this.hasHeaderRow = hasHeaderRow;
            this.columns = dataStoreFactory.GetColumns(this.name);
        }

        protected override void Extract(TriggerInstruction triggerInstruction)
        {
            Logger.DebugFormat("[{0}] extracting from triggerInstruction=[{1}]", this.name, triggerInstruction);
            
            string[] lines = File.ReadAllLines(this.file);
            DataTable dataTable = new DataTable(name);

            foreach (string column in this.columns.Keys)
            {
                dataTable.Columns.Add(column);
            }

            for (int i = this.hasHeaderRow ? 1 : 0; i < lines.Length; i++)
            {
                dataTable.Rows.Add(lines[i].Split(','));
            }

            this.Commit(dataTable);
        }
    }
}